const Koa = require('koa');
const app = new Koa();
const multer = require('koa-multer');
var router = require('koa-router')();
const cors = require('koa2-cors');


var storage = multer.diskStorage({
    //文件保存路径
    destination: function (req, file, cb) {
        cb(null, 'uploads/')
    },
    //修改文件名称
    filename: function (req, file, cb) {
        var fileFormat = (file.originalname).split(".");
        cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
    }
})
var upload = multer({ storage: storage });

// 具体参数我们在后面进行解释
app.use(cors({
    origin: function (ctx) {
        return "http://localhost:3000"; 
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))

router.post('/upload', upload.single('file'), async (ctx, next) => {
    ctx.body = {
        status:1,
        filename: ctx.req.file.filename//返回文件名
    }
})

router.get('/get', async (ctx, next) => {
    ctx.body = '恭喜 __小简__ 你成功登陆了'
})

app
    .use(router.routes())
    .use(router.allowedMethods());

app.listen(5656, function () {
    console.log('成功的启动在5656端口')
});
